<template>
  <div class="app-container fullscreen">
    <div class="headBar">
      <img src="@/assets/images/njHead.png" alt="" />
      <div class="headName">
        农机大数据平台
      </div>
    </div>
    <div class="container">
      <div id="left">
        <div class="box">
          <img src="@/assets/images/njTip.png" alt="" class="njTip" />
          <div class="title">
            <img src="@/assets/images/njIcon.png" alt="" class="njIcon" />
            <div class="titleName">近一周上线情况</div>
          </div>
          <div class="content">
            <c-1 height="350px" :chartData="chartDataC1"></c-1>
          </div>
        </div>
        <div class="box">
          <img src="@/assets/images/njTip.png" alt="" class="njTip" />
          <div class="title">
            <img src="@/assets/images/njIcon.png" alt="" class="njIcon" />
            <div class="titleName">农机类型</div>
          </div>
          <div class="content">
            <c-2 height="350px" :chartData="chartDataC2"></c-2>
          </div>
        </div>
      </div>
      <div id="center">
        <div class="map">
          <map-cluster ref="map" @init="mapInit" />
        </div>
        <div v-if="deviceList" class="bottom">
          <ProgressYuan
            color="#45a9f2"
            text="总车辆"
            :value="deviceList.eqList.length"
            :deg-num="(deviceList.eqList.length / deviceList.eqList.length) * 180"
          />
          <ProgressYuan
            color="#f29146"
            text="作业"
            :value="deviceList.workingCount"
            :deg-num="(deviceList.workingCount / deviceList.eqList.length) * 180"
          />
          <ProgressYuan
            color="#30cb13"
            text="在线"
            :value="deviceList.onLineCount"
            :deg-num="(deviceList.onLineCount / deviceList.eqList.length) * 180"
          />
          <ProgressYuan
            color="red"
            text="离线"
            :value="deviceList.offLineCount"
            :deg-num="(deviceList.offLineCount / deviceList.eqList.length) * 180"
          />
          <ProgressYuan
            color="#248ad0"
            text="当月在线"
            :value="deviceList.monthCount"
            :deg-num="(deviceList.monthCount / deviceList.eqList.length) * 180"
          />
          <ProgressYuan
            color="#fbdc4d"
            text="当日在线"
            :value="deviceList.dayCount"
            :deg-num="(deviceList.dayCount / deviceList.eqList.length) * 180"
          />
        </div>
      </div>
      <div class="right">
        <div class="box">
          <img src="@/assets/images/njTip.png" alt="" class="njTip" />
          <div class="title">
            <img src="@/assets/images/njIcon.png" alt="" class="njIcon" />
            <div class="titleName">久富集锦</div>
          </div>
          <div class="content"></div>
        </div>
      </div>
    </div>
    <!-- <dy-charts-iframe src="https://dycharts.com/xshow/index.html?id=d5b4c80a7382879697b01e242601fb9c" /> -->
    <div v-if="device" class="popover-wrapper" @click="device = null;
              deviceMark.setIcon(deviceMark.eqIcon)">
      <div ref="popover" class="popover" @click.stop="">
        <div class="popover-title">{{ device.eq_type }}</div>
        <div class="popover-content">
          <div>
            农机制造编号:
            <router-link :to="'../A1/equipmentDetial/detail/' + device.eq_code">
              <div style="display: inline;text-decoration: underline;color: blue;cursor: pointer;">{{device.eq_code}}</div>
            </router-link>
          </div>
          <div>车辆类型: {{ device.eq_module }}</div>
          <div>当前状态: {{ device.online ? '在线' : '离线' }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/**   农机大数据平台 */
import { getDeviceList } from '@/api/device'
import MapCluster from '@/components/MapCluster'
import ProgressYuan from '../../../components/ProgressYuan/index.vue'
import C1 from './c1.vue'
import C2 from './c2.vue'
import coordtransform from 'coordtransform'

// import onlineMark from '@/assets/images/tractor.svg'
// import offlineMark from '@/assets/images/tractor_gray.svg'

import eq1aMark from '@/assets/images/eq1_a.png'
import eq2aMark from '@/assets/images/eq2_a.png'
import eq3aMark from '@/assets/images/eq3_a.png'
import eq4aMark from '@/assets/images/eq4_a.png'
import eq1bMark from '@/assets/images/eq1_b.png'
import eq1cMark from '@/assets/images/eq1_c.png'
import eq2bMark from '@/assets/images/eq2_b.png'
import eq2cMark from '@/assets/images/eq2_c.png'
import eq3bMark from '@/assets/images/eq3_b.png'
import eq3cMark from '@/assets/images/eq3_c.png'
import eq4bMark from '@/assets/images/eq4_b.png'
import eq4cMark from '@/assets/images/eq4_c.png'

export default {
  components: {
    C1,
    C2,
    MapCluster,
    ProgressYuan
  },
  data() {
    return {
      // onlineMark:onlineMark,
      // offlineMark:offlineMark,
      chartDataC1:[],
      chartDataC2:[],
      eq1aMark:eq1aMark,
      eq2aMark:eq2aMark,
      eq3aMark:eq3aMark,
      eq4aMark:eq4aMark,
      eq1bMark:eq1bMark,
      eq1cMark:eq1cMark,
      eq2bMark:eq2bMark,
      eq2cMark:eq2cMark,
      eq3bMark:eq3bMark,
      eq3cMark:eq3cMark,
      eq4bMark:eq4bMark,
      eq4cMark:eq4cMark,
      deviceList: null,
      device: null,
      deviceMark: null,
      left_line_data: { expectedData: [1, 2, 3, 4, 5, 6, 7], actualData: [3, 4, 5, 6, 7, 8, 9] },
      coordtransform
    }
  },
  methods: {
    async mapInit(AMap, map) {
      let cluster, markers = [];
      this.deviceList = await getDeviceList()
      // console.log('this.deviceList.typeCount',this.deviceList.typeCount)
      this.chartDataC1 = this.deviceList.weekOnline
      this.chartDataC2 = this.deviceList.typeCount
      // const { Marker,MarkerClusterer } = AMap
      var points = this.deviceList.eqList
      points = points.map((item) => {
        var newPoints = this.coordtransform.wgs84togcj02(item.longitude, item.latitude)
        // console.log("lnglat",item.lnglat)
        // console.log("newPoints",newPoints)
        item.longitude = newPoints[0];
        item.latitude = newPoints[1];
        item.lnglat = newPoints;
        return item
      })
      // console.log("points==",points)
      var count = points.length;

      function clusterMarkers() {
        var markerList = [];
        var marker = new AMap.Marker({
          map: map,
        })
        console.log("clusterMarkers")
        markerList.push(marker);
        return markerList;
      }
      var clusterIndexSet = {
        province: {
          minZoom: 2,
          maxZoom: 7,
        },
        city: {
          minZoom: 7,
          maxZoom: 9,
        },
        district: {
          minZoom: 9,
          maxZoom: 11,
        },
        township: {
          minZoom: 11,
          maxZoom: 13,
        },
        eq_code: {
          minZoom: 13,
          maxZoom: 22,
        },
      };
      function getStyle(context) {
        var clusterData = context.clusterData; // 聚合中包含数据
        var index = context.index; // 聚合的条件
        var count = context.count; // 聚合中点的总数
        var marker = context.marker; // 聚合绘制点 Marker 对象
        var color = [
          '139,101,8',
          '8,60,156',
          '66,130,198',
          '107,174,214',
          '78,200,211',
        ];
        var indexs = ['province','city','district','township','eq_code'];
        var i = indexs.indexOf(index['mainKey']);
        var text = clusterData[0][index['mainKey']];
        // var size = Math.round(40 + Math.pow(count / points.length, 1 / 5) * 40);
        var size = 50;
        if(i <= 3){
          var extra = '<span class="showCount">'+ context.count +'</span>';
          text = '<span class="showName">'+ text +'</span>';
          text = text + extra;
          var style = {
            bgColor: 'rgba(' + color[i] + ',.8)',
            borderColor: 'rgba(' + color[i] + ',1)',
            text: text,
            size: size,
            index: i,
            color: '#ffffff',
            textAlign: 'center',
            boxShadow: '0px 0px 5px rgba(0,0,0,0.8)'
          }
          return style;
        } else {
          size = 12 * text.length + 20;
          var style = {
            bgColor: 'rgba(' + color[i] + ',.8)',
            borderColor: 'rgba(' + color[i] + ',1)',
            text: text,
            size: size,
            index: i,
            color: '#ffffff',
            textAlign: 'center',
            boxShadow: '0px 0px 5px rgba(0,0,0,0.8)'
          }
          return style;
        }

      }
      function getPosition(context) {
        var key = context.index.mainKey;
        var dataItem = context.clusterData && context.clusterData[0];
        var districtName = dataItem[key];
        return null;
        // if(!district[districtName]) {
        //   return null;
        // }
        // var center = district[districtName].center.split(',');
        // var centerLnglat = new AMap.LngLat(center[0], center[1]);
        // return centerLnglat;
      }

      // 自定义聚合点样式
      const _this = this
      const eqIcon1a = require('../../../assets/images/eq1_a.png')
      const eqIcon2a = require('../../../assets/images/eq2_a.png')
      const eqIcon3a = require('../../../assets/images/eq3_a.png')
      const eqIcon4a = require('../../../assets/images/eq4_a.png')
      const eqIcon1b = require('../../../assets/images/eq1_b.png')
      const eqIcon1c = require('../../../assets/images/eq1_c.png')
      const eqIcon2b = require('../../../assets/images/eq2_b.png')
      const eqIcon2c = require('../../../assets/images/eq2_c.png')
      const eqIcon3b = require('../../../assets/images/eq3_b.png')
      const eqIcon3c = require('../../../assets/images/eq3_c.png')
      const eqIcon4b = require('../../../assets/images/eq4_b.png')
      const eqIcon4c = require('../../../assets/images/eq4_c.png')
      const eqIcon5a = require('../../../assets/images/eq5_a.png')
      const eqIcon5b = require('../../../assets/images/eq5_b.png')
      const eqIcon5c = require('../../../assets/images/eq5_c.png')
      function _renderClusterMarker (context) {
        var clusterData = context.clusterData; // 聚合中包含数据
        var index = context.index; // 聚合的条件
        var count = context.count; // 聚合中点的总数
        var marker = context.marker; // 聚合点标记对象
        var styleObj = getStyle(context);
        // 自定义点标记样式
        var div = document.createElement('div');
        if(styleObj.index <= 3) {
          div.className = 'amap-cluster';
          div.style.backgroundColor = styleObj.bgColor;
          div.style.width = styleObj.size + 'px';
          div.style.height = styleObj.size + 'px';
          // 自定义点击事件
          context.marker.on('click', function(e) {
            var curZoom = map.getZoom();
            if(curZoom < 20){
              curZoom += 2;
            }
            map.setZoomAndCenter(curZoom, e.lnglat);
          });
          div.style.border = 'solid 1px ' + styleObj.borderColor;
          div.style.borderRadius = styleObj.size + 'px';
          div.innerHTML = styleObj.text;
          div.style.color = styleObj.color;
          div.style.textAlign = styleObj.textAlign;
          div.style.boxShadow = styleObj.boxShadow;

          context.marker.setContent(div)
        }else{
          var eqObj = clusterData[0]
          // var margIcon
          // if(eqObj.eq_type == "插秧机")
          //   margIcon = eqObj.online ? _this.eq2bMark : eq2cMark
          // else if(eqObj.eq_type == "收割机")
          //   margIcon = eqObj.online ? _this.eq1bMark : eq1cMark
          // else if(eqObj.eq_type == "拖拉机")
          //   margIcon = eqObj.online ? _this.eq3bMark : eq3cMark
          // else
          //   margIcon = eqObj.online ? _this.eq4bMark : eq4cMark

          let eqIcon;
          let eqIconActive;
          if(eqObj.eq_type == "插秧机") {
            eqIcon = eqObj.online ? eqIcon2b : eqIcon2c
            eqIconActive = eqIcon2a
          }
          else if(eqObj.eq_type == "收割机") {
            eqIcon = eqObj.online ? eqIcon1b : eqIcon1c
            eqIconActive = eqIcon1a
          }
          else if(eqObj.eq_type == "拖拉机") {
            eqIcon = eqObj.online ? eqIcon3b : eqIcon3c
            eqIconActive = eqIcon3a
          }
          else if(eqObj.eq_type == "直播机") {
            eqIcon = eqObj.online ? eqIcon5b : eqIcon5c
            eqIconActive = eqIcon5a
          }
          else {
            eqIcon = eqObj.online ? eqIcon4b : eqIcon4c
            eqIconActive = eqIcon4a
          }

          context.marker.setIcon(eqIcon)

          // if(eqObj.online == 1){
          //   margIcon = _this.onlineMark
          // }else{
          //   margIcon = _this.offlineMark
          // }
          // div.className = 'amap-cluster';
          // // div.style.backgroundColor = styleObj.bgColor;
          // div.style.backgroundImage ='url(' + margIcon + ')';
          // div.style.width =  '64px';
          // div.style.height = '64px';
          // div.style.borderRadius = '38px';
          // 自定义点击事件
          context.marker.on('click', function(e) {
            const { lng, lat } = marker.getPosition()
            const pixel = map.lngLatToContainer(new AMap.LngLat(lng, lat))
            const x = pixel.x + _this.$refs.map.$el.getBoundingClientRect().x
            const y = pixel.y + _this.$refs.map.$el.getBoundingClientRect().y + 150

            _this.device = eqObj
            const __this = _this
            _this.$nextTick(() => {
              marker.eqIcon = marker.getIcon()
              marker.setIcon(eqIconActive)
              __this.deviceMark = marker

              // console.log("__this.$refs.popover",__this.$refs.popover)
              __this.$refs.popover.style.left = x + 'px'
              __this.$refs.popover.style.top = y + 'px'
            })
          });


        }

        // 自定义聚合点标记显示位置
        var position = getPosition(context);
        if(position){
          context.marker.setPosition(position);
        }
        context.marker.setAnchor('center');

      };

      cluster = new AMap.IndexCluster(map, points, {
        renderClusterMarker: _renderClusterMarker,
        clusterIndexSet: clusterIndexSet,
      });
      console.log("cluster",cluster)



      // const total = new Marker({
      //   map,
      //   position: [116.3683244,39.915085],
      //   icon: require('../DeviceMap/marker.svg'),
      //   label: {
      //     content: this.deviceList.eqList.length,
      //     offset: [-32, 0]
      //   },
      //   title: `${this.deviceList.eqList.length}台`,
      //   clickable: true
      // })
      // const online = require('../DigitalMap/tractor.svg')
      // const offline = require('../DigitalMap/tractor_gray.svg')
      // markers = this.deviceList.eqList.map(
      //   device =>
      //     new Marker({
      //       // map,
      //       icon: device.online ? online : offline,
      //       position: [device.longitude, device.latitude],
      //       title: `${device.eq_type}-${device.eq_code}`
      //     })
      //     // new Marker({
      //     //   map,
      //     //   visible: true,
      //     //   icon: device.online ? online : offline,
      //     //   position: [device.longitude, device.latitude],
      //     //   title: `${device.eq_type}-${device.eq_code}`
      //     // })
      // )
      // addCluster()
      // function addCluster() {
      //   if (cluster) {
      //     cluster.setMap(null);
      //   } else {
      //     // 如果不设置renderClusterMarker，聚合点为默认样式
      //     cluster = new MarkerClusterer(map, markers, {
      //       gridSize: 50,
      //     });
      //   }
      // }

      // console.log(cluster.getMap())


      // console.log(markerList)
      //
      // const cluster = new AMap.MarkerClusterer(map, markerList, {gridSize: 80});
      //
      // console.log("cluster",cluster)

      // const provinceMarkerList = this.deviceList.provinceList.map(
      //   device => {
      //     new Marker({
      //       map,
      //       position: [device.longitude, device.latitude],
      //       icon: require('../DeviceMap/marker.svg'),
      //       label: {
      //         content: device.count,
      //         offset: [-32, 0]
      //       },
      //       title: `${device.name}:${device.count}台`,
      //       clickable: true
      //     })
      //   }
      // )


      // total.on('click', () => map.setZoomAndCenter(9.6, [116.3683244,39.915085]))
      //
      // markers.forEach((marker, i) => {
      //   marker.on('click', () => {
      //     const { lng, lat } = marker.getPosition()
      //     const pixel = map.lngLatToContainer(new AMap.LngLat(lng, lat))
      //     const x = pixel.x + this.$refs.map.$el.getBoundingClientRect().x
      //     const y = pixel.y + this.$refs.map.$el.getBoundingClientRect().y
      //     this.device = this.deviceList.eqList[i]
      //     this.$nextTick(() => {
      //       this.$refs.popover.style.left = x + 'px'
      //       this.$refs.popover.style.top = y + 'px'
      //     })
      //   })
      // })
      // map.on('zoomend', ({ target }) => {
      //   console.log("target.getZoom()",target.getZoom())
      //   // if(target.getZoom() < 5){
      //   //   provinceMarkerList.forEach(marker => marker.show())
      //   // }
      //
      //   if (target.getZoom() > 9) {
      //     markerList.forEach(marker => marker.show())
      //     total.hide()
      //   } else {
      //     markerList.forEach(marker => marker.hide())
      //     total.show()
      //   }
      // })
    }
  }
}
</script>

<style lang="scss" scoped>

.app-container {
  //width: 1920px;
  //height: 1080px;
  width: 100%;
  height: 100%;
  padding: 0;
  box-sizing: border-box;
  background: #010429;
}
.container {
  width: calc(100% - 40px);
  height: calc(100% - 144px);
  display: flex;
  margin: 0 20px;
}
.box {
  width: 100%;
  border: 4px solid #121c3b;
  padding: 16px;
  border-radius: 16px;
  box-sizing: border-box;
  position: relative;
  background: #0a182d;
  margin-bottom: 20px;
  .njTip {
    position: absolute;
    right: 20px;
    top: -10px;
    width: 60px;
  }
  .title {
    display: flex;
    align-items: center;
    color: #2cedf1;
    font-size: 24px;
    position: relative;
    font-weight: bold;
    .njIcon {
      width: 40px;
      margin-right: 20px;
    }
  }
}
.headBar {
  width: 100%;
  height: 144px;
  color: #fff;
  position: relative;
  .headName {
    text-align: center;
    position: absolute;
    font-size: 40px;
    left: 50%;
    top: 30%;
    transform: translate(-50%, 0);
  }
}
#left {
  width: 25%;
  height: 100%;
  .content {
    .list {
      .listItem {
        .itemName {
          width: 150px;
        }
        width: 100%;
        display: flex;
        align-items: center;
        color: #fff;
        margin-top: 20px;
      }
    }
  }
}
#center {
  width: 50%;
  margin: 0 10px;
  .map {
    width: 100%;
    height: 780px;
  }
  .bottom {
    margin-top: 32px;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}
.right {
  width: 25%;
  height: 100%;
}

.popover-wrapper {
  position: fixed;
  inset: 0;
  .popover {
    position: absolute;
    background: white;
    transform: translate(-50%, -102%);
    white-space: nowrap;
    border-radius: 8px;
    .popover-title {
      font-weight: bold;
      font-size: 20px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);
      padding: 8px 16px;
    }
    .popover-content {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 20px;
      padding: 8px 16px;
    }
  }


}
</style>

<style>
.amap-cluster {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
  vertical-align:middle;
}
.showName {
  font-size: 12px;
}
.showCount,.showName {
  display: block;
  /*text-overflow: ellipsis;*/
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
